package cc.rengu.redp.bizimpl.utils;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.http.HttpServletRequest;
import java.io.*;
import java.lang.reflect.Field;
import java.math.BigDecimal;
import java.net.HttpURLConnection;
import java.net.JarURLConnection;
import java.net.URL;
import java.net.URLDecoder;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.jar.JarEntry;
import java.util.jar.JarFile;
import java.util.regex.Pattern;

/**
 * @Author: 刘玉亮
 * @CreateDate: 2021/6/10 0010 17:06
 * @UpdateDate: 2021/6/10 0010 17:06
 * @Version: 1.0
 * @Description:
 */

public class Common {
    private static final Logger log = LoggerFactory.getLogger(Common.class);
    private static final int DEF_DIV_SCALE = 10;

    public Common() {
    }

    public static double convertSourData(String dataStr) throws Exception {
        if (dataStr != null && !"".equals(dataStr)) {
            return Double.valueOf(dataStr);
        } else {
            log.error("convertSourData =====  convert error!");
            throw new NumberFormatException("convert error!");
        }
    }

    public static boolean isBlank(String s) {
        return null == s || "".equals(s) || "".equals(s.trim()) || "null".equalsIgnoreCase(s);
    }

    public static boolean isNotBlank(String s) {
        return null != s && !"".equals(s) && !"".equals(s.trim()) && !"null".equalsIgnoreCase(s);
    }

    public static boolean isBlank(Object o) {
        if (null == o) {
            return true;
        } else {
            String s = o.toString();
            return "".equals(s) || "".equals(s.trim()) || "null".equalsIgnoreCase(s);
        }
    }

    public static boolean isNotBlank(Object o) {
        if (o == null) {
            return false;
        } else {
            String s = o.toString();
            return !"".equals(s) && !"".equals(s.trim()) && !"null".equalsIgnoreCase(s);
        }
    }

    public static String fromUsage(long free, long total) {
        Double d = (new BigDecimal(free * 100L / total)).setScale(1, 4).doubleValue();
        return String.valueOf(d);
    }

    public static String formatDouble(Double b) {
        BigDecimal bg = new BigDecimal(b);
        return bg.setScale(2, 4).toString();
    }

    public static String fromDateH() {
        DateFormat format1 = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
        return format1.format(new Date());
    }

    public static String fromDateY() {
        DateFormat format1 = new SimpleDateFormat("yyyy-MM-dd");
        return format1.format(new Date());
    }

    public static int toInt(String str) {
        return toInt(str, 0);
    }

    public static int toInt(String str, int defaultValue) {
        if (str == null) {
            return defaultValue;
        } else {
            try {
                return Integer.parseInt(str);
            } catch (NumberFormatException var3) {
                return defaultValue;
            }
        }
    }

    public static boolean isNumber(String str) {
        if (isBlank(str)) {
            return false;
        } else {
            char[] chars = str.toCharArray();
            int sz = chars.length;
            boolean hasExp = false;
            boolean hasDecPoint = false;
            boolean allowSigns = false;
            boolean foundDigit = false;
            int start = chars[0] == '-' ? 1 : 0;
            int i;
            if (sz > start + 1 && chars[start] == '0' && chars[start + 1] == 'x') {
                i = start + 2;
                if (i == sz) {
                    return false;
                } else {
                    while(i < chars.length) {
                        if ((chars[i] < '0' || chars[i] > '9') && (chars[i] < 'a' || chars[i] > 'f') && (chars[i] < 'A' || chars[i] > 'F')) {
                            return false;
                        }

                        ++i;
                    }

                    return true;
                }
            } else {
                --sz;

                for(i = start; i < sz || i < sz + 1 && allowSigns && !foundDigit; ++i) {
                    if (chars[i] >= '0' && chars[i] <= '9') {
                        foundDigit = true;
                        allowSigns = false;
                    } else if (chars[i] == '.') {
                        if (hasDecPoint || hasExp) {
                            return false;
                        }

                        hasDecPoint = true;
                    } else if (chars[i] != 'e' && chars[i] != 'E') {
                        if (chars[i] != '+' && chars[i] != '-') {
                            return false;
                        }

                        if (!allowSigns) {
                            return false;
                        }

                        allowSigns = false;
                        foundDigit = false;
                    } else {
                        if (hasExp) {
                            return false;
                        }

                        if (!foundDigit) {
                            return false;
                        }

                        hasExp = true;
                        allowSigns = true;
                    }
                }

                if (i < chars.length) {
                    if (chars[i] >= '0' && chars[i] <= '9') {
                        return true;
                    } else if (chars[i] != 'e' && chars[i] != 'E') {
                        if (chars[i] == '.') {
                            return !hasDecPoint && !hasExp ? foundDigit : false;
                        } else if (allowSigns || chars[i] != 'd' && chars[i] != 'D' && chars[i] != 'f' && chars[i] != 'F') {
                            if (chars[i] != 'l' && chars[i] != 'L') {
                                return false;
                            } else {
                                return foundDigit && !hasExp;
                            }
                        } else {
                            return foundDigit;
                        }
                    } else {
                        return false;
                    }
                } else {
                    return !allowSigns && foundDigit;
                }
            }
        }
    }

    public static List<String> removeSameItem(List<String> list) {
        List<String> difList = new ArrayList();
        Iterator i$ = list.iterator();

        while(i$.hasNext()) {
            String t = (String)i$.next();
            if (t != null && !difList.contains(t)) {
                difList.add(t);
            }
        }

        return difList;
    }

    public static String toIpAddr(HttpServletRequest request) {
        String ip = request.getHeader("X-Forwarded-For");
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("Proxy-Client-IP");
        }

        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("WL-Proxy-Client-IP");
        }

        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("HTTP_CLIENT_IP");
        }

        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("HTTP_X_FORWARDED_FOR");
        }

        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getRemoteAddr();
        }

        return ip;
    }

    public static String generateFileName(String fileName) {
        DateFormat format = new SimpleDateFormat("yyyyMMddHHmmss");
        String formatDate = format.format(new Date());
        int random = (new Random()).nextInt(10000);
        int position = fileName.lastIndexOf(".");
        String extension = fileName.substring(position);
        return formatDate + random + extension;
    }

    public static String getInputHtmlUTF8(String urlStr) {
        URL url = null;

        try {
            url = new URL(urlStr);
            HttpURLConnection httpsURLConnection = (HttpURLConnection)url.openConnection();
            httpsURLConnection.setRequestMethod("GET");
            httpsURLConnection.setConnectTimeout(5000);
            httpsURLConnection.connect();
            if (httpsURLConnection.getResponseCode() == 200) {
                InputStream inputStream = httpsURLConnection.getInputStream();
                String data = readHtml(inputStream, "UTF-8");
                inputStream.close();
                return data;
            } else {
                return null;
            }
        } catch (Exception var5) {
            return null;
        }
    }

    public static String getInputHtmlGBK(String urlStr) {
        URL url = null;

        try {
            url = new URL(urlStr);
            HttpURLConnection httpsURLConnection = (HttpURLConnection)url.openConnection();
            httpsURLConnection.setRequestMethod("GET");
            httpsURLConnection.setConnectTimeout(5000);
            httpsURLConnection.connect();
            if (httpsURLConnection.getResponseCode() == 200) {
                InputStream inputStream = httpsURLConnection.getInputStream();
                String data = readHtml(inputStream, "GBK");
                inputStream.close();
                return data;
            } else {
                return null;
            }
        } catch (Exception var5) {
            log.error("error = [{}]", var5);
            return null;
        }
    }

    public static String readHtml(InputStream inputStream, String uncode) throws Exception {
        InputStreamReader input = new InputStreamReader(inputStream, uncode);
        BufferedReader bufReader = new BufferedReader(input);
        String line = "";
        StringBuilder contentBuf = new StringBuilder();

        while((line = bufReader.readLine()) != null) {
            contentBuf.append(line);
        }

        return contentBuf.toString();
    }

    public static byte[] readInputStream(InputStream inputStream) {
        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
        byte[] buffer = new byte[1024];
        boolean var3 = false;

        Object var5;
        try {
            int len;
            while((len = inputStream.read(buffer)) != -1) {
                byteArrayOutputStream.write(buffer, 0, len);
            }

            return byteArrayOutputStream.toByteArray();
        } catch (IOException var15) {
            log.error("error = [{}]", var15);
            var5 = null;
        } finally {
            try {
                byteArrayOutputStream.close();
            } catch (IOException var14) {
                log.error("error = [{}]", var14);
            }

        }

        return (byte[])var5;
    }


    public static String findUserSessionId(HttpServletRequest request) {
        Object obj = request.getSession().getAttribute("userSessionId");
        return obj != null ? obj.toString() : null;
    }

    public static Object findUserSession(HttpServletRequest request) {
        return request.getSession().getAttribute("userSession");
    }

    public static double sub(double v1, double v2) {
        BigDecimal b1 = new BigDecimal(Double.toString(v1));
        BigDecimal b2 = new BigDecimal(Double.toString(v2));
        return b1.subtract(b2).doubleValue();
    }

    public static double add(double v1, double v2) {
        BigDecimal b1 = new BigDecimal(Double.toString(v1));
        BigDecimal b2 = new BigDecimal(Double.toString(v2));
        return b1.add(b2).doubleValue();
    }

    public static double mul(double v1, double v2) {
        BigDecimal b1 = new BigDecimal(Double.toString(v1));
        BigDecimal b2 = new BigDecimal(Double.toString(v2));
        return b1.multiply(b2).doubleValue();
    }

    public static double div(double v1, double v2) {
        return div(v1, v2, 10);
    }

    public static double div(double v1, double v2, int scale) {
        if (scale < 0) {
            throw new IllegalArgumentException("The scale must be a positive integer or zero");
        } else {
            BigDecimal b1 = new BigDecimal(Double.toString(v1));
            BigDecimal b2 = new BigDecimal(Double.toString(v2));
            return b1.divide(b2, scale, 4).doubleValue();
        }
    }

    public static String trimComma(String para) {
        if (isNotBlank(para)) {
            return para.endsWith(",") ? para.substring(0, para.length() - 1) : para;
        } else {
            return "";
        }
    }
    public static String htmltoString(String content) {
        if (content == null) {
            return "";
        } else {
            String html = content.replace("'", "&apos;");
            html = html.replaceAll("&", "&amp;");
            html = html.replace("\"", "&quot;");
            html = html.replace("\t", "&nbsp;&nbsp;");
            html = html.replace(" ", "&nbsp;");
            html = html.replace("<", "&lt;");
            html = html.replaceAll(">", "&gt;");
            return html;
        }
    }

    public static String stringtohtml(String content) {
        if (content == null) {
            return "";
        } else {
            String html = content.replace("&apos;", "'");
            html = html.replaceAll("&amp;", "&");
            html = html.replace("&quot;", "\"");
            html = html.replace("&nbsp;&nbsp;", "\t");
            html = html.replace("&nbsp;", " ");
            html = html.replace("&lt;", "<");
            html = html.replaceAll("&gt;", ">");
            return html;
        }
    }

    public static boolean isNumeric1(String str) {
        Pattern pattern = Pattern.compile("[0-9]*");
        return pattern.matcher(str).matches();
    }

    public static String mysqltoString(String content) {
        if (content == null) {
            return "";
        } else {
            String html = content.replace("'", "\\'");
            html = html.replace("%", "\\%");
            html = html.replace("\"", "\\\"");
            return html;
        }
    }

    public static Set<Class<?>> getClasses(String pack) {
        Set<Class<?>> classes = new LinkedHashSet();
        boolean recursive = true;
        String packageName = pack;
        String packageDirName = pack.replace('.', '/');

        try {
            Enumeration dirs = Thread.currentThread().getContextClassLoader().getResources(packageDirName);

            while(true) {
                label67:
                while(dirs.hasMoreElements()) {
                    URL url = (URL)dirs.nextElement();
                    String protocol = url.getProtocol();
                    if ("file".equals(protocol)) {
                        String filePath = URLDecoder.decode(url.getFile(), "UTF-8");
                        findAndAddClassesInPackageByFile(packageName, filePath, recursive, classes);
                    } else if ("jar".equals(protocol)) {
                        try {
                            JarFile jar = ((JarURLConnection)url.openConnection()).getJarFile();
                            Enumeration entries = jar.entries();

                            while(true) {
                                JarEntry entry;
                                String name;
                                int idx;
                                do {
                                    do {
                                        if (!entries.hasMoreElements()) {
                                            continue label67;
                                        }

                                        entry = (JarEntry)entries.nextElement();
                                        name = entry.getName();
                                        if (name.charAt(0) == '/') {
                                            name = name.substring(1);
                                        }
                                    } while(!name.startsWith(packageDirName));

                                    idx = name.lastIndexOf(47);
                                    if (idx != -1) {
                                        packageName = name.substring(0, idx).replace('/', '.');
                                    }
                                } while(idx == -1 && !recursive);

                                if (name.endsWith(".class") && !entry.isDirectory()) {
                                    String className = name.substring(packageName.length() + 1, name.length() - 6);

                                    try {
                                        classes.add(Class.forName(packageName + '.' + className));
                                    } catch (ClassNotFoundException var15) {
                                        log.error("error = [{}]", var15);
                                    }
                                }
                            }
                        } catch (IOException var16) {
                            log.error("error = [{}]", var16);
                        }
                    }
                }

                return classes;
            }
        } catch (IOException var17) {
            log.error("error = [{}]", var17);
            return classes;
        }
    }

    public static void findAndAddClassesInPackageByFile(String packageName, String packagePath, final boolean recursive, Set<Class<?>> classes) {
        File dir = new File(packagePath);
        if (dir.exists() && dir.isDirectory()) {
            File[] dirfiles = dir.listFiles(new FileFilter() {
                public boolean accept(File file) {
                    return recursive && file.isDirectory() || file.getName().endsWith(".class");
                }
            });
            File[] arr$ = dirfiles;
            int len$ = dirfiles.length;

            for(int i$ = 0; i$ < len$; ++i$) {
                File file = arr$[i$];
                if (file.isDirectory()) {
                    findAndAddClassesInPackageByFile(packageName + "." + file.getName(), file.getAbsolutePath(), recursive, classes);
                } else {
                    String className = file.getName().substring(0, file.getName().length() - 6);

                    try {
                        classes.add(Thread.currentThread().getContextClassLoader().loadClass(packageName + '.' + className));
                    } catch (ClassNotFoundException var12) {
                        log.error("error = [{}]", var12);
                    }
                }
            }

        }
    }
}
